//
//  HttpManager.m
//  XiangMi_Novel
//
//  Created by Botao on 2019/1/14.
//  Copyright © 2019 zk. All rights reserved.
//

#import "HttpManager.h"
#import "NetConnectModel.h"

@interface HttpManager ()
@property (nonatomic, strong, readwrite) AFHTTPSessionManager *manager;

@end

@implementation HttpManager

+ (HttpManager *)shareInstance{
    static HttpManager * s_instance_dj_singleton = nil ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (s_instance_dj_singleton == nil) {
            s_instance_dj_singleton = [[HttpManager alloc] init];
        }
    });
    return (HttpManager *)s_instance_dj_singleton;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

#pragma mark - Lazy Initializer
- (AFHTTPSessionManager *)manager {
    if (_manager == nil) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
        AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
        _manager.responseSerializer = serializer;
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript",@"text/plain",nil];
        
    }
    return _manager;
}

//登录接口
- (void)loginRequestWithUrl:(NSString *)url param:(NSDictionary *)paramDic token:(NSString *)token Complete:(completeWithDicBlock)dicBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript", nil];
    //[manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    [manager POST:url parameters:paramDic progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSString *token = [response.allHeaderFields objectForKey:@"token"];
        if (token == nil) {
            token = @"";
        }
        NSInteger code = [[dataDict objectForKey:@"code"] integerValue];
        NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:dataDict];
        [mutableDict setObject:token forKey:@"token"];
        
        //[Dao updateUserInfoWithToken:token];
        
        dicBlock(code,mutableDict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *responseObject = (NSHTTPURLResponse *)task.response;
        NSLog(@"POST <%@>, Failure:%@", task.response.URL, error);
        dicBlock(responseObject.statusCode ,nil);
    }];
}

//绑定接口
- (void)bindingRequestWithUrl:(NSString *)url param:(NSDictionary *)paramDic Complete:(completeWithDicBlock)dicBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript", nil];
    [manager POST:url parameters:paramDic progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSString *token = [response.allHeaderFields objectForKey:@"token"];
        if (token == nil) {
            token = @"";
        }
        NSInteger code = [[dataDict objectForKey:@"code"] integerValue];
        NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:dataDict];
        [mutableDict setObject:token forKey:@"token"];
        dicBlock(code,mutableDict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *responseObject = (NSHTTPURLResponse *)task.response;
        NSLog(@"POST <%@>, Failure:%@", task.response.URL, error);
        dicBlock(responseObject.statusCode ,nil);
    }];
}


- (NSData *)zipNSDataWithImage:(UIImage *)sourceImage{
    //进行图像的画面质量压缩
    NSData *data = UIImagePNGRepresentation(sourceImage);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
            data=UIImageJPEGRepresentation(sourceImage, 0.7);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(sourceImage, 0.8);
        }else if (data.length>200*1024) {
            //0.25M-0.5M
            data=UIImageJPEGRepresentation(sourceImage, 0.9);
        }
    }
    return data;
}

//上传图片
- (void)requestUploadImageWithUrl:(NSString *)url param:(NSDictionary *)param file:(id)file token:(NSString *)token Complete:(completeWithDicBlock)dicBlock
{
    [ZK_HUD showUIBlockingIndicatorWithText:@""];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript", nil];
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [manager POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         //把图片转换为二进制流
         NSData *imageData = UIImagePNGRepresentation(file);
         //[self zipNSDataWithImage:file];
         NSString *imageName = [[NSUUID UUID].UUIDString stringByAppendingString:@".png"];
         [formData appendPartWithFileData :imageData name:[param objectForKey:@"image"] fileName:imageName mimeType:@"image/png"];
         NSLog(@"");
     } progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         [ZK_HUD hideUIBlockingIndicator];
         NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
         NSString *code = [[dataDict objectForKey:@"code"] stringValue];
         if ([code isEqualToString:@"0"]) {
             //请求成功
             dicBlock(0,dataDict);
         }else{
             dicBlock([[dataDict objectForKey:@"code"] integerValue],dataDict);
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [ZK_HUD hideUIBlockingIndicator];
         NSHTTPURLResponse *responseObject = (NSHTTPURLResponse *)task.response;
         NSLog(@"POST <%@>, Failure:%@", task.response.URL, error);
         dicBlock(responseObject.statusCode ,@{@"msg":@"请求失败"});
     }];
}


//通用整合接口，参数：requestWay，url，dict
- (void)commonRequestWithRequestWay:(NSString *)requestWay url:(NSString *)url loadStr:(NSString *)loadStr param:(NSDictionary *)paramDic Complete:(completeWithDicBlock)dicBlock netCompletBlock:(void(^)(NSString *netStr))netBlock
{
    if (![[NetConnectModel shareInstance] isConnectionAvailable]) {
        netBlock(@"请检查网络连接");
        return;
    }
    if ([loadStr isEqualToString:@"0"]) {
        
    }else if ([loadStr isEqualToString:@""]){
        [ZK_HUD showUIBlockingIndicatorWithText:@""];
        //[ZK_HUD showUIBlockingIndicatorWithText:@"" withTimeout:3];
        //[ZK_HUD showTimedAlertWithTitle:@"11" text:@"22" withTimeout:5];
    }else {
        [ZK_HUD showUIBlockingIndicatorWithText:loadStr];
    }
    if ([requestWay isEqualToString:@"get"])
    {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript", nil];
        [manager.requestSerializer setValue:[paramDic objectForKey:@"token"] forHTTPHeaderField:@"token"];
        
        [manager GET:url parameters:paramDic progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [ZK_HUD hideUIBlockingIndicator];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            if ([[dic objectForKey:@"errmsg"] isEqualToString:@"success"]) {
                dicBlock(0,dic);
                return ;
            }
            NSString *code = [[dic objectForKey:@"code"] stringValue];
            if ([code isEqualToString:@"0"]) {
                //请求成功
                dicBlock(0,dic);
            }else{
                dicBlock([code integerValue],dic);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [ZK_HUD hideUIBlockingIndicator];
            NSHTTPURLResponse *responseObject = (NSHTTPURLResponse *)task.response;
            NSLog(@"POST <%@>, Failure:%@", task.response.URL, error);
            if (responseObject.statusCode == 0) {
                dicBlock(-1 ,@{@"msg":@"请求失败"});
            }else{
                dicBlock(responseObject.statusCode,@{@"msg":@"请求失败"});
            }
        }];
    }else if ([requestWay isEqualToString:@"post"]){
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript", nil];
        [manager.requestSerializer setValue:[paramDic objectForKey:@"token"] forHTTPHeaderField:@"token"];
        [manager POST:url parameters:paramDic progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [ZK_HUD hideUIBlockingIndicator];
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            if ([[[dataDict objectForKey:@"errno"] stringValue] isEqualToString:@"0"]) {
                dicBlock(0,dataDict);
                return ;
            }
            NSString *code = [[dataDict objectForKey:@"code"] stringValue];
            if ([code isEqualToString:@"0"]) {
                //请求成功
                dicBlock(0,dataDict);
            }else if ([code isEqualToString:@"1002"]){
                dicBlock(1002,dataDict);
                [Tools showMessage:@"token过期"];
                //token过期
                [self presentLoginVC];
            }else if ([code isEqualToString:@"1003"]){
                dicBlock(1003,dataDict);
                [Tools showMessage:@"账号在其他设备登录"];
                //账号在其他设备登录
                [self presentLoginVC];
            }else if ([code isEqualToString:@"159"]){
                dicBlock(159,dataDict);
            }else{
                dicBlock([[dataDict objectForKey:@"code"] integerValue],dataDict);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [ZK_HUD hideUIBlockingIndicator];
            NSHTTPURLResponse *responseObject = (NSHTTPURLResponse *)task.response;
            NSLog(@"POST <%@>, Failure:%@", task.response.URL, error);
            if (responseObject.statusCode == 0) {
                dicBlock(responseObject.statusCode ,@{@"msg":@"请检查网络连接状况"});
            }else if (responseObject.statusCode == 401){
                //dicBlock(responseObject.statusCode ,@{@"msg":@"请求失败"});
                [self presentLoginVC];
            }else {
                dicBlock(responseObject.statusCode ,@{@"msg":@"请求失败"});
            }
            
        }];
    }else if ([requestWay isEqualToString:@"json_post"]){
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript", nil];
        [manager.requestSerializer setValue:[paramDic objectForKey:@"token"] forHTTPHeaderField:@"token"];
        [manager POST:url parameters:paramDic progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [ZK_HUD hideUIBlockingIndicator];
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSString *code = [[dataDict objectForKey:@"code"] stringValue];
            if ([code isEqualToString:@"0"]) {
                //请求成功
                dicBlock(0,dataDict);
            }else if ([code isEqualToString:@"1003"]){
                dicBlock(1003,dataDict);
                [Tools showMessage:@"账号在其他设备登录"];
                //账号在其他设备登录
                [self presentLoginVC];
            }else{
                dicBlock([[dataDict objectForKey:@"code"] integerValue],dataDict);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [ZK_HUD hideUIBlockingIndicator];
            NSHTTPURLResponse *responseObject = (NSHTTPURLResponse *)task.response;
            NSLog(@"POST <%@>, Failure:%@", task.response.URL, error);
            dicBlock(responseObject.statusCode ,nil);
        }];
    }else if ([requestWay isEqualToString:@""]){
        
    }
    
}

- (void)presentLoginVC
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"presentLoginVC" object:nil];
}


// 是否隐藏登录和分享~~~
- (void)getFlagParam:(NSDictionary *)paramDic Complete:(completeWithDicBlock)dicBlock
{
    NSString *url = [RequestUrl iosFlag];
    self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [self.manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        dicBlock(200,dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *responseObject = (NSHTTPURLResponse *)task.response;
        NSLog(@"POST <%@>, Failure:%@", task.response.URL, error);
        dicBlock(responseObject.statusCode ,nil);
    }];
}


/*
 
- (void)request
{
    [[HttpManager shareInstance] commonRequestWithRequestWay:@"post" url:@"" loadStr:@"" param:@{} Complete:^(NSInteger code, NSDictionary * _Nonnull dictionary) {
        if (code == 0) {
            
            [self.collectionView reloadData];
        }else{
            [Tools showMessage:dictionary[@"msg"]];
        }
    } netCompletBlock:^(NSString * _Nonnull netStr) {
        [Tools showMessage:netStr];
    }];
}
 
 */
@end


